<?php

namespace App\Controller\webSocket;

use App\Common\RedisUtils;
use App\Service\common\switchService;
use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;


class WebSocketController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    use RedisUtils;

    /**
     * 服务连接
     * @param $server
     * @param $request
     * @return void
     */
    public function onOpen($server, $request): void
    {
        $message = $request->fd . ' 号app客户端已连接';
        echo $message;
        $pushData['accessType'] = 'connect';
        $pushData['data']['msg'] = $message;
        $server->push($request->fd, json_encode($pushData, 256));
    }

    /**
     * 接受消息
     * @param $server
     * @param $frame
     * @return void
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function onMessage($server, $frame): void
    {
        $result = make(switchService::class)->getSwitchService($frame->fd, $frame->data);
        var_dump($frame->fd . ' 发送数据 ' . $frame->data);
//        echo '发给 ' . $frame->fd . ' 号客户端的消息：' . $frame->data;
        //    $server->push($frame->fd, $frame->data);
    }

    /**
     * 服务关闭
     * @param $server
     * @param int $fd
     * @param int $reactorId
     * @return void
     */
    public function onClose($server, int $fd, int $reactorId): void
    {
        $message = $fd . '断开连接,处理线程是 ' . $reactorId . PHP_EOL;
        echo $message;
    }
}